﻿using AutoMapper;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.MES.Common;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 班次管理（错误代码：101001）
    /// </summary>
    public class WorkshopDutyMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取班次对象
        /// </summary>
        /// <param name="dutyId">班次ID</param>
        /// <returns>班次对象</returns>
        public VWorkshopDuty GetDuty(int dutyId)
        {
            var entity = mesDb.WorkshopDuties.AsNoTracking().FirstOrDefault(_ => _.PkId == dutyId && _.Valid);
            return Mapper.Map<VWorkshopDuty>(entity);
        }

        /// <summary>
        /// 编辑班次
        /// </summary>
        /// <param name="model">班次对象</param>
        public void EditDuty(VWorkshopDuty model)
        {
            var workshop = new WorkshopMgr().GetWorkshop(model.WorkshopCode);
            if (workshop == null)
            {
                throw new MultiLanBizException(101001);// "车间不存在");
            }
            model.WorkshopName = workshop.WorkshopName;
            if (model.PkId <= 0)
            {
                var exist = mesDb.WorkshopDuties.FirstOrDefault(_ => _.WorkshopCode == model.WorkshopCode && _.DutyName == model.DutyName && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(101002);// "班次名称已存在，请更换其他名称");
                }
                model.Status = CommonStatus.Normal;
                model.CreateTime = DateTime.Now;
                model.ModifyBy = 0;
                var entity = Mapper.Map<WorkshopDuty>(model);
                mesDb.WorkshopDuties.Add(entity);
            }
            else
            {
                var exist = mesDb.WorkshopDuties.FirstOrDefault(_ => _.WorkshopCode == model.WorkshopCode && _.DutyName == model.DutyName && _.PkId != model.PkId && _.Valid);
                if (exist != null)
                {
                    throw new MultiLanBizException(101002);// "班次名称已存在，请更换其他名称");
                }
                var entity = mesDb.WorkshopDuties.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
                if (entity == null)
                {
                    throw new MultiLanBizException(101003);// "班次不存在或已被删除，无法编辑");
                }
                entity.WorkshopCode = model.WorkshopCode;
                entity.WorkshopName = model.WorkshopName;
                entity.DutyName = model.DutyName;
                entity.StartTime = model.StartTime;
                entity.EndTime = model.EndTime;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 查询班次列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        /// <param name="workshopCode">车间ID</param>
        /// <param name="status">状态</param>
        /// <returns>班次列表</returns>
        public List<VWorkshopDuty> QueryDuties(int pageIndex, int pageSize, out int total, string workshopCode, CommonStatus? status)
        {
            var query = mesDb.WorkshopDuties.Where(_ => _.Valid);
            if (status.HasValue)
            {
                query = query.Where(_ => _.Status == status.Value);
            }
            if (!string.IsNullOrWhiteSpace(workshopCode))
            {
                query = query.Where(_ => _.WorkshopCode == workshopCode);
            }

            total = query.Count();
            query = query.OrderBy(_ => _.WorkshopCode).ThenBy(_ => _.DutyName);
            var entities = pageSize <= 0 ? query.ToList() : query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var models = Mapper.Map<List<VWorkshopDuty>>(entities);
            return models;
        }

        /// <summary>
        /// 查询班次列表
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        /// <param name="pageSize">页面容量</param>
        /// <param name="total">总数</param>
        /// <param name="workshopCode">车间ID</param>
        /// <param name="status">状态</param>
        /// <returns>班次列表</returns>
        public List<VWorkshopDuty> QueryDuties(string workshopCode)
        {
            var entities = mesDb.WorkshopDuties.Where(_ => _.WorkshopCode == workshopCode && _.Status == CommonStatus.Normal && _.Valid).ToList();
            var models = Mapper.Map<List<VWorkshopDuty>>(entities);
            return models;
        }

        /// <summary>
        /// 获取当前车间班次
        /// </summary>
        /// <param name="workshopCode">车间代码</param>
        /// <returns>班次对象</returns>
        public VWorkshopDuty GetCurDuty(string workshopCode)
        {
            VWorkshopDuty duty = null;
            var duties = QueryDuties(workshopCode);
            foreach (var item in duties)
            {
                if (!item.StartTime.HasValue || !item.EndTime.HasValue)
                {
                    continue;
                }
                var timeSpan = DateTime.Now.TimeOfDay;
                if ((item.StartTime.Value <= item.EndTime.Value && timeSpan >= item.StartTime.Value && timeSpan < item.EndTime.Value)
                    || (item.StartTime.Value > item.EndTime.Value && (timeSpan >= item.StartTime.Value || timeSpan < item.EndTime.Value)))
                {
                    duty = item;
                    break;
                }
            }
            return duty;
        }

        /// <summary>
        /// 修改班次状态
        /// </summary>
        /// <param name="model">班次对象</param>
        public void ModifyStatus(VWorkshopDuty model)
        {
            var exist = mesDb.WorkshopDuties.FirstOrDefault(_ => _.PkId == model.PkId && _.Valid);
            if (exist == null)
            {
                throw new MultiLanBizException(101004);// "班次不存在，无法修改状态");
            }
            exist.Status = model.Status;
            exist.ModifyBy = model.ModifyBy;
            exist.ModifyTime = DateTime.Now;
            mesDb.SaveChanges();
        }
    }
}
